package com.neusoft.oauth2server.controller;


import com.neusoft.oauth2server.api.CommonResult;
import com.neusoft.oauth2server.api.IErrorCode;
import com.neusoft.oauth2server.api.ResultCode;
import com.neusoft.oauth2server.dto.Oauth2TokenDto;
import com.neusoft.oauth2server.entity.Users;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.security.Principal;
import java.util.Map;

/**
 * 自定义Oauth2获取令牌接口
 * Created by macro on 2020/7/17.
 */
@RestController
@RequestMapping("/oauth")
public class AuthController {
    private final static String PROVIDER_URL = "http://39.105.147.252:10001/";
    @Autowired
    private TokenEndpoint tokenEndpoint;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * Oauth2登录认证
     */
    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public CommonResult<Oauth2TokenDto> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        String username = parameters.get("username");
        String password = parameters.get("password");

        Users users = restTemplate.getForObject(PROVIDER_URL + "getUserByUsername?username=" + username, Users.class);
        if (users == null) {
            return CommonResult.failed(ResultCode.USERNAME_NOT_EXIST);
        } else {

            if (passwordEncoder.matches(password, users.getUserPassword())) {
                OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
                Oauth2TokenDto oauth2TokenDto = new Oauth2TokenDto(oAuth2AccessToken.getValue(), oAuth2AccessToken.getRefreshToken().getValue(), "Bearer ", oAuth2AccessToken.getExpiresIn());
                return CommonResult.success(oauth2TokenDto);
            } else {
                return CommonResult.failed(ResultCode.PASSWORD_WRONG);
            }
        }


    }


}
